<!--同步分析-->
<template>
  <div class="container" v-loading="globalLoading">
    <div class="target-container" >
      <el-card class="box-card target-card">
        <el-scrollbar max-height="350px">
          <span>目标输入：</span>
          <p></p>
          <el-form :model="chartFrom" label-width="120px">
            <el-form-item label="图表名称">
              <el-input v-model="chartFrom.chartName"  placeholder="给图表取个名字" />
            </el-form-item>
            <el-form-item label="分析目标">
              <el-input
                  v-model="chartFrom.target"
                  style="width: 500px"
                  :rows="2"
                  type="textarea"
                  placeholder="请输入你的分析目标"
              />
            </el-form-item>
            <el-form-item label="图表类型">
              <el-select v-model="chartFrom.chartType" placeholder="图表类型" >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
              <el-text class="mx-1" size="small" style="margin-left: 5px;color: #909399; cursor:default">请使用合理的图表类型，否则可能会出现图表展示错乱情况</el-text>
            </el-form-item>
            <el-form-item label="上传excel数据">
              <el-upload
                  ref="uploadFile"
                  class="upload-demo"
                  :auto-upload="false"
                  :on-change="loadJsonFromFile">
                <template #trigger>
                  <el-button type="primary">上传文件<el-icon class="el-icon--right"><Upload /></el-icon></el-button>
                </template>
              </el-upload>
              <el-text class="mx-1" size="small" style="margin-left: 5px;color: #909399;margin-bottom: 10px;cursor:default;" :class="{fileInfo:isShowFileInfo}">{{fileInfoWarn}}</el-text>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :loading="globalLoading" @click="toAnalyze">AI 智能分析</el-button>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </el-card>

      <el-card class="result-card">
        <el-scrollbar max-height="310px" class="result-card-scrollbar">
          <el-text v-if="!elEmptyIsShow" class="mx-1">图表分析：{{chartData.genChartResult}}</el-text>
          <el-empty description="暂无分析结论" v-if="elEmptyIsShow"
                    element-loading-text="分析结果生成中"
                    :element-loading-spinner="svg"
                    element-loading-svg-view-box="-10, -10, 50, 50"
                    element-loading-background="rgba(122, 122, 122, 0.8)"/>
        </el-scrollbar>
      </el-card>
    </div>

    <!--  ==============================-->
    <!--  图表展示-->
    <div class="chart-container">
      <div id="echarts-container"
           element-loading-text="图表生成中"
           :element-loading-spinner="svg"
           element-loading-background="rgba(122, 122, 122, 0.8)">
        <el-empty description="暂无数据图表" v-if="elEmptyIsShow" />
      </div>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import chartTypeOption from "../../../../common/options.js"
import {ElMessage} from "element-plus";
import axios from "axios";
import { inject } from 'vue';
import {Upload} from "@element-plus/icons-vue";
import Chart from "./Chart.vue";
import * as echarts from "echarts";
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

// const chartData = inject("chartData");
const chartData = reactive({
  chartId:'', //图表id
  genChartResult:'', //图表分析结果
  genChartCode:'', //图表的echarts option参数
})

const globalLoading = ref(false); //全局loading效果


//图表类型选项.
const options = chartTypeOption;

//智能分析按钮loading
// const loading = ref(false);

const elEmptyIsShow =ref(true)

const chartFrom = ref({
    chartName:'',//图表名字
    target:'', //分析目标
    chartType:'' //图表类型
})

const uploadFile = ref([]); //文件
const fileInfoWarn = ref("最大支持10MB（仅支持excel文件）");
const isShowFileInfo = ref(false);

//当上传文件变动
const loadJsonFromFile = (file, fileList) =>{
    uploadFile.value = fileList
}

//智能分析按钮
const toAnalyze = async ()=>{
   if(chartFrom.value.chartName.trim() === ''){
     ElMessage.error("未输入图表名称");
     return;
   }
  if(chartFrom.value.target.trim() === ''){
    ElMessage.error("为输入分析目标");
    return;
  }
  if(chartFrom.value.chartType.trim() === ''){
    ElMessage.error("未选择图表类型");
    return;
  }

    console.log(uploadFile.value.length)
    if(uploadFile.value.length === undefined){
      ElMessage.error("未上传文件");
      return;
    }

  globalLoading.value = true;
  elEmptyIsShow.value =false;
    // 解析上传的文件
    if(uploadFile.value.length > 0 && uploadFile.value[0].name != null){
        let fileInfo = uploadFile.value[0].raw;
        const maxFileSize = 1024 * 1024 * 10 //最大10MB
        //这里还需对文件大小进行检验
        if(fileInfo.size > maxFileSize){
            fileInfoWarn.value = "文件过大，请重新上传文件";
            isShowFileInfo.value = true;
            ElMessage.error(fileInfoWarn.value);
            return;
        }
        fileInfoWarn.value = "最大支持3MB（仅支持excel文件）";
        isShowFileInfo.value = false;
        let formData = new FormData();
        formData.append('file',uploadFile.value[0].raw);
        // formData.append('data',chartFrom.value);
        formData.append('name',chartFrom.value.chartName)
        formData.append('goal',chartFrom.value.target)
        formData.append('chartType',chartFrom.value.chartType)
        const instance = axios.create({
            withCredentials: true // 允许携带cookie
        });
        // chartData.loading = true;
        await instance.post('http://localhost:8101/api/analyse/gen', formData, {
            headers: {
                'Content-Type': 'multipart/form-data' // 设置请求头，指定为multipart/form-data
            }
        }).then(res => {
          console.log(res);
          res = res.data;
          if(res.code === 0 || res.message === 'ok'){
            let result = res.data;
            chartData.chartId = result.chartId;
            chartData.genChartResult = result.genChartResult;
            let option = {};
            try {
              option = JSON.parse(result.genChartCode)
            } catch (e) {
              option = result.genChartCode;
              chartData.genChartCode = option;
              elEmptyIsShow.value =false;
              globalLoading.value = false;
              render(option); // 渲染图表
              return;
            }
            if(Object.keys(option).includes('grid')){
              delete option.grid;
            }
            if(!Object.keys(option).includes('toolbox')){
              option.toolbox ={};
            }
            option.toolbox ={
                show:true,
                feature:{
                  dataView:{
                    readOnly:false
                  },
                  dataZoom:{},
                  magicType:{
                    type: ['line','bar']
                  },
                  restore:{},
                  saveAsImage:{}
                }
            }
            console.log("处理过后的option");
            console.log(option);
            chartData.genChartCode = option;
            elEmptyIsShow.value =false;
            globalLoading.value = false;
            render(option); // 渲染图表
          }else{
            elEmptyIsShow.value =true;
            globalLoading.value = false;
            ElMessage.error(res.message);
          }
        })
    }else{
      elEmptyIsShow.value =true;
      globalLoading.value = false;
    }
  globalLoading.value = false;
}

/**
 * 图表渲染
 * @param option
 */
const render = (option) => {
  const chartDom = document.getElementById('echarts-container');
  const myChart = echarts.init(chartDom);
  console.log("要渲染的option");
  console.log(option);
  option && myChart.setOption(option);
}


</script>

<style scoped lang="less">
.container{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-around;
}
.chart-container{
  width: 53%;
  height: 95%;
  margin-top: 10px;
  #echarts-container{
    width: 100%  ;
    height: 95%;
  }
}
.el-card{
    border: none !important;
}
.result-card{
    width: 100%;
    margin-top: 20px;
    height: 40%;
  .result-card-scrollbar{
    display: block;
    width: 600px;
  }
    //background: #8c939d;
  .result-card-text{
    //margin-top: -10px;
    width: 100%;
    background: red;
  }
}
.target-card{
    height: 55%;
}
.el-form{
    margin-top: 0;
}
.target-container{
    width: 43%;
    margin-top: 10px;
    .target{
        display: flex;
        justify-content: center;
        .el-input{
            width: 400px;
        }
    }
    .upload{
        display: flex;
        justify-content: center;
    }
    .type{
        display: flex;
        justify-content: center;
    }
}

.fileInfo{
    color: red !important;
}
</style>